const puppeteer = require("puppeteer-core");
const gs = require("ghostscript4js");
const fs = require("fs");

(async () => {
  const browser = await puppeteer.launch({
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    headless: true,
    args: ["--disable-pdf-tagging"],
  });
  const html = `<!DOCTYPE html>
  <html lang="en">
  
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人封面</title>
    <style>
       
       #cover .avatar {
        width: 96px;
        height: 96px;
        object-fit: cover;
       }
       
      #cover .mock-img {
        width: 96px;
        height: 96px;
        background: url('https://imgcdpee.cdpee.org.cn/16755153945114.jpg') no-repeat;
        background-size: cover; 
      }
    </style>
  
  </head>
  
  <body>
    <div id="cover">
      <p>个人简历</p>
      <img class="avatar" src="https://imgcdpee.cdpee.org.cn/16755153945114.jpg" alt="6.1M">
      <!--<img class="avatar" src="https://pic.lvmama.com/uploads/pc/place2/2017-11-24/19e96e3c-ba34-4dc4-8b17-62b3aa595cf9.jpg" alt="6.4M">
      <img class="avatar" src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4a00961c22854974b1811007be4446f6~tplv-k3u1fbpfcp-watermark.image">
      <img class="avatar" src="https://steemitimages.com/DQmXtdHCxEo8tiGK1vNsAnxUDNQNBB7Kq5feqRn9oVuPNfk/artmix1.jpg">
      <img class="avatar" src="https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4a00961c22854974b1811007be4446f6~tplv-k3u1fbpfcp-watermark.image" alt="" srcset=""
      > 
      <p class="mock-img"></p> -->
    </div>
  </body>
  
  </html>`;
  const page = await browser.newPage();
  await page.setDefaultNavigationTimeout(0);
  await page.setContent(html, { waitUntil: "networkidle0" });
  const buffer = await page.pdf({
    // path: "./public/render.pdf",
    format: "a4",
    printBackground: true,
    displayHeaderFooter: true,
    "-webkit-print-color-adjust": "exact",
  });
  // 保存 PDF 缓冲区到临时文件
  fs.writeFileSync("temp.pdf", buffer);
  // Ghostscript 选项
  const inputPath = "temp.pdf";
  const outputPath = "output.pdf";

  const options = [
    '-sDEVICE=pdfwrite',
    '-dCompatibilityLevel=1.4',
    '-dPDFSETTINGS=/ebook',
    '-dNOPAUSE',
    '-dQUIET',
    '-dBATCH',
    `-sOutputFile=output.pdf`,
    inputPath
  ];
  // 使用 Ghostscript 处理 PDF 缓冲区
  gs.execute(options, (err) => {
    if (err) {
      console.error(err);
    } else {
      // 删除临时文件
      fs.unlinkSync("temp.pdf");
      console.log(`PDF file compressed and saved to ${outputPath}`);
    }
  });
  
 
  await browser.close();
})();
